package org.ilc.socketserver.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.ilc.socketserver.Header;

/**
 * @author malongbo
 */
public class Context {
    protected boolean matched = false;
    protected int matcheCount = 0;
    private int receiveHeaderLength = 0;
    private int receiveBodyLength = 0;
    private Header header = null;
    IoBuffer headerBuffer = IoBuffer.allocate (1024).setAutoExpand (true);
    IoBuffer bodyBuffer = IoBuffer.allocate (1024).setAutoExpand (true);
    byte [] headerBytes = null;
    byte [] bodyBytes = null;

    public Header getHeader () throws Exception {
        if (this.matched) {
            if ( null == header) {
                if (headerBytes == null) {
                    headerBuffer.flip ();
                    headerBytes = new byte[headerBuffer.limit ()];
                    headerBuffer.get (headerBytes);
                }
                this.header = new Header (headerBytes);
            }
        }
        return header;
    }

    public byte [] getHeaderBytes () {
        if (headerBytes == null) {
            headerBuffer.flip ();
            headerBytes = new byte[headerBuffer.limit ()];
            headerBuffer.get (headerBytes);
        }
        return this.headerBytes;
    }

    public byte [] getBodyBytes () {
        if (bodyBytes == null) {
            bodyBuffer.flip ();
            bodyBytes = new byte[bodyBuffer.limit ()];
            bodyBuffer.get (bodyBytes);
        }
        return bodyBytes;
    }
    public void writeHead (byte b) {
        headerBuffer.put (b);
        receiveHeaderLength++;
    }

    public void writeBody (byte [] bytes) {
        bodyBuffer.put (bytes);
        receiveBodyLength += bytes.length;
    }

    public int bodyLength() {
        return receiveBodyLength;
    }

    public int headLength() {
        return receiveHeaderLength;
    }

    public void destroy() {
        this.receiveBodyLength=0;
        this.receiveHeaderLength=0;
        this.matcheCount=0;
        this.matched=false;
        if (bodyBuffer != null) {
            bodyBuffer.free ();
            bodyBuffer.clear ();
        }
        if (headerBuffer != null) {
            headerBuffer.free ();
            headerBuffer.clear ();
        }

        if (headerBytes != null) {
            headerBytes = null;
        }
        if (bodyBytes != null) {
            bodyBytes = null;
        }

        if (header != null) {
            header = null;
        }
    }
}
